package com.platform.modules.acme.utils;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import javax.annotation.WillClose;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author DavenTsang
 * @Description Files Operation
 */
public class FileUtils {

    /**
     * 打包文件夹
     *
     * @param targetPath zip存放目录
     * @param zipName    zip名字
     * @param sourcePath 需要打包的文件夹
     * @throws ZipException
     * @throws FileNotFoundException
     */
    static public void zip(String targetPath, String zipName, String sourcePath)
            throws ZipException, FileNotFoundException {
        File zipSrc = new File(targetPath);
        // 不存在目录则创建
        if (!zipSrc.exists()) {
            zipSrc.mkdirs();
        }
        // 批次文件夹

        File subDir = new File(sourcePath);
        if (!subDir.exists()) {
            subDir.mkdirs();
        }

        // 压缩参数
        ZipParameters params = new ZipParameters();
        params.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式
        params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别
        /*
         * 可设置zip密码 if (StringUtils.isNotBlank(password)) {
         * params.setEncryptFiles(true);
         * params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);// 加密方式
         * params.setPassword(password.toCharArray()); }
         */
        ZipFile zip = new ZipFile(targetPath + File.separator + zipName);// 压缩文件存放路径

        zip.addFolder(subDir, params);
    }


    /**
     * 删除某个文件夹下的所有文件夹和文件
     *
     * @param delpath
     * @return boolean
     * @throws FileNotFoundException IOException
     */
    public static boolean deletefile(String delpath) throws Exception {
        File file = new File(delpath);
        if (file.isDirectory()) {
            String[] filelist = file.list();
            for (String delFile : filelist) {
                File delfile = new File(delpath + File.separator + delFile);
                if (delfile.isDirectory()) {
                    deletefile(delpath + File.separator + delFile);
                } else
                    delfile.delete();
            }
            System.out.println("deleting empty dir：" + file.getPath() + ",is delelted：" + file.delete());
        } else
            System.out.println("deleting file ：" + file.getPath() + ",is deleted：" + file.delete());
        return true;
    }

    public static void writeFile(String path, String name, @WillClose InputStream input) {
        FileOutputStream out = null;
        try {
            File filePath = new File(path);
            if (!filePath.exists())
                filePath.mkdirs();
            out = new FileOutputStream(filePath + "." + name);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = input.read(buffer, 0, len)) != -1) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 把byte[]文件流，指定路径和文件名保存
     *
     * @param bfile    需要保存的文件流
     * @param filePath 保存路径
     * @param fileName 保存文件名
     * @param flag     是否追加
     * @throws IOException
     */
    public static void saveFile(byte[] bfile, String filePath, String fileName, boolean flag) throws IOException {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            File file = newFile(filePath, fileName);

            fos = new FileOutputStream(file, flag);
            bos = new BufferedOutputStream(fos);
            if (file.length() > 0) {
                bos.write("\r".getBytes());
            }
            bos.write(bfile);
        } catch (IOException e) {
            throw e;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static File newFile(String filePath, String fileName) {
        File file = null;
        File dir = new File(filePath);
        if (!(dir.exists() && dir.isDirectory())) {//判断文件目录是否存在
            dir.mkdirs();
        }

        if (filePath.lastIndexOf("/") == filePath.length() - 1 || filePath.lastIndexOf("\\") == filePath.length() - 1) {
            file = new File(filePath + fileName);
        } else {
            file = new File(filePath + File.separator + fileName);
        }
        return file;
    }

    /**
     * 创建文件夹，如果存在则直接返回
     *
     * @param path
     * @return
     */
    public static File newFolder(String path) {
        File dir = new File(path);
        if (!(dir.exists() && dir.isDirectory())) {
            dir.mkdir();
        }
        return dir;

    }


    public static void main(String[] args) throws ZipException, IOException {
        List<File> fs = new ArrayList<>();
        fs.add(new File("D:\\test\\111.txt"));
        File f = new File("D:\\test\\222.txt");
        FileInputStream fi = new FileInputStream(f);
        /*
         * byte[] b = new byte[1024]; FileOutputStream fo = new FileOutputStream(new
         * File("D:\\test\\222.txt")); int len = 0; while((len = fi.read(b))!=-1) {
         * fo.write(b,0,len); } fo.close(); fi.close();
         */

    }
}
